package com.itheima.reggie.handler;

import com.itheima.reggie.common.Result.Result;
import com.itheima.reggie.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String>  sqlExceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info("异常信息:{}", ex.getMessage());
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String name = message.split(" ")[2];
            return Result.error(name + "已存在");
        } else {
            return Result.error("未知错误");
        }
    }

    @ExceptionHandler
    public Result<String> CustomExceptionHandler(BaseException ex){
        log.info("异常信息:{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
}
